/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hathor.networking.reciever;

import com.hathor.batch.batchWatch;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Kenneth
 */
public class BatchHandler {

    private BatchExecutor batExecutor;
    private Socket sock;

    public BatchHandler(Socket sock) {
        this.sock = sock;
    }

    public void manageBatch() throws IOException {
        // receive file into temp file, just to be executed, then removed from the filesystem
        File tempMission = File.createTempFile("tempMission", ".bat");
        tempMission.deleteOnExit();
        ObjectInputStream is = new ObjectInputStream(sock.getInputStream());
        FileWriter fw = new FileWriter(tempMission);
        try {
            List<String> xFerredBatchLines = (ArrayList<String>) is.readObject();
            String targetBatch = xFerredBatchLines.get(0);
            if (targetBatch.startsWith(">KILL")) {
                targetBatch = xFerredBatchLines.get(0).replace(">KILL ", "");
                if (batchWatch.getBatchExecutor(targetBatch) != null) {
                    batchWatch.getCurrentBatchExecutor().terminate();
                    System.out.println("Destroyed current process");
                }
                System.out.println("No process was started, cannot kill");
            } else if (targetBatch.startsWith(">NEW")) {
                targetBatch = xFerredBatchLines.get(0).replace(">NEW ", "");
                batchWatch.registerBatchExecutor(targetBatch, batExecutor);
                System.out.println("Writing to temporary batch file...");
                for (String aLine : xFerredBatchLines) {
                    if (!aLine.startsWith(">NEW")) {
                        System.out.println(aLine);
                        fw.write(aLine + System.lineSeparator());
                        fw.flush();
                    }
                }
                fw.close();
                batExecutor = new BatchExecutor(tempMission);
                Thread batExecutorThread = new Thread(batExecutor);
                batExecutorThread.start();
            }
        } catch (ClassNotFoundException ex) {
            System.err.println(ex);
        } finally {
            batchWatch.setCurrentBatchExecutor(batExecutor);
            tempMission.deleteOnExit();
            if (fw != null) {
                fw = null;
            }
        }
    }
}
